
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/constants.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_medal_entity.dart';
import 'package:osc/models/entity/osc_skill_radar_map_entity.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/entity/widget_item/user_center_item.dart';
import 'package:osc/models/local_data/user_center_item_data.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/blog/blog_list.dart';
import 'package:osc/ui/pages/my/activity_list.dart';
import 'package:osc/ui/pages/my/question_list.dart';
import 'package:osc/ui/pages/tweet/tweet_list.dart';
import 'package:osc/ui/pages/user/user_ability_cobweb_view.dart';
import 'package:osc/ui/pages/user/user_friend_list.dart';
import 'package:osc/ui/widgets/medal/medal_list_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';


class UserProfile extends StatefulWidget{
  final int userId;
  final String nickName;
  const UserProfile({Key key, @required this.userId, this.nickName}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new UserProfileState(userId, nickName);
  }
}

class UserProfileState extends State<UserProfile> with SingleTickerProviderStateMixin {
  int userId;
  String nickName;
  UserProfileState(this.userId, this.nickName);

  OscUser user;
  OscSkillRadarMapEntity skillRadarMapEntity;
  List<OscMedal> medals;

  String userName = "";
  String portrait;
  bool isLogin = false;
  int gender = 0;
  int tweetCount = 0;
  int blogCount = 0;
  int questionsAndAnswersCount = 0;
  int discussCount = 0;
  int focusCount = 0;
  int fansCount = 0;

  int relation = 4;//1:相互关注, 2:关注, 3:粉丝, 4:无
  String relationImageName;


  List<UserCenterItem> myItems;
  HttpRepository httpRepository;


  double expandedHeight = 0;
  double appBarHeight = 0;

  int maxScore = 100;
  List<double> scores = [0, 0, 0, 0, 0, 0];

  RefreshController refreshController;
  ScrollController scrollController;
  TabController tabController;


  @override
  void initState() {
    super.initState();
    appBarHeight = Dimens.view_app_bar_height_mine;

    myItems = UserCenterItemData().getItems();
    refreshController = RefreshController(initialRefresh: true);
    scrollController = ScrollController();
    tabController = TabController(length: 6, vsync: this);
    tabController.addListener((){
      setState(() {

      });
    });
    httpRepository = new HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
    scrollController.dispose();
    tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    expandedHeight = ScreenUtil.getInstance().screenWidth;
    return Scaffold(
      body: SmartRefresher(
          controller: refreshController,
        onRefresh: refresh,
        enablePullUp: false,
        child: buildCustomScrollView(),
      ),
    );
  }

  buildCustomScrollView(){
    return NestedScrollView(
      controller: scrollController,
      headerSliverBuilder: (BuildContext context, bool inBox){
        return [
          SliverAppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Theme.of(context).primaryColor,
            expandedHeight: expandedHeight*4/5,
            titleSpacing: 0,
            title: buildProfile(),
            actions: <Widget>[
              buildAction(getRelationImageName(relation), (){
                reverserRelation(id: userId);
              }),
              buildAction("ic_menu_more", (){
                showMoreDialog();
              }),
            ],
            primary: true,//是否预留高度,ture时在状态栏下，false 最上面
            snap: false,//折叠效果，与floating结合使用，如果为true则floating必须为true,就是往下滑一点整个大背景就显示全部，往上滑动整个导航内容就隐藏
            floating: false,//是否随滑动隐藏标题,则滑动到最上面再滑动是否隐藏标题，ture隐藏
            pinned: true,//是否固定导航在顶部，true 固定，false不固定，再上滑导航隐藏
            flexibleSpace: FlexibleSpaceBar(
              collapseMode: CollapseMode.parallax,
              centerTitle: true,
              background: SizedBox(
                width: expandedHeight*4/5,
                height: expandedHeight*1/5,
                child: CustomPaint(
                  painter: UserAbilityCobwebView(scores: scores, maxRadius: expandedHeight/8, skills: Constant.SKILLS),
                ),
              ),
            ),
            bottom: PreferredSize(
              child: buildBottom(),
              preferredSize: Size.fromHeight(Dimens.view_item_height_normal),
            ),
          )
        ];
      },
      body: buildTabBarView(),
    );
  }

  buildBottom(){
    return Container(
      child: Column(
        children: <Widget>[
          MedalListWidget(userId: userId, gender: gender, medals: medals,),
          buildTabBar(),
        ],
      ),
    );
  }

  buildTabBar(){
    return Container(
      color: Color(0x36000000),
      child: TabBar(
        labelPadding: EdgeInsets.zero,
        tabs: [
          buildTab("猿圈", tweetCount, 0),
          buildTab("博客", blogCount, 1),
          buildTab("问答", questionsAndAnswersCount, 2),
          buildTab("讨论", discussCount, 3),
          buildTab("关注", focusCount, 4),
          buildTab("粉丝", fansCount, 5),
        ],
        controller: tabController,
      ),
    );
  }

  buildTab(String data, int number, int index){
    bool selected = tabController.index == index;
    Color color = selected? Colors.white : Colors.white70;
    return Padding(
        padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_smaller),
      child: Column(
        children: <Widget>[
          SmallWidgets.buildText("${StringUtil.intNumber2String(num: number, fractionDigits: 1)}", color, Dimens.font_sp14),
          SmallWidgets.buildText(data, color, Dimens.font_sp12),
        ],
      ),
    );
  }

  buildTabBarView(){
    if(userId == null){
      return Container(
        alignment: Alignment.center,
        child: SizedBox(
          width: Dimens.view_item_icon_height_biggest,
          height: Dimens.view_item_icon_height_biggest,
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return TabBarView(
          controller: tabController,
          children: [
            TweetList(userId: userId,),
            BlogList(authorUid: userId,),
            QuestionList(authorId: userId,),
            ActivityList(userId: userId,),
            UserFriendList(relation: 1, userId: userId,),
            UserFriendList(relation: 0, userId: userId,),
          ]
      );
    }
  }


  buildProfile(){
    return Padding(
        padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal),
      child: Row(
        children: <Widget>[
          buildPortrait(),
          SmallWidgets.buildText(userName, Colors.white, Dimens.font_sp14),
        ],
      ),
    );
  }

  buildPortrait(){
    Widget child;
    if(user == null || StringUtil.isEmpty(user.portrait)){
      child = Image.asset(PdUtil.getImagePath("ic_author"), width: 50,);
    } else {
      child = OscPortraitWidget(
        id: userId,
        portraitImageUrl: portrait,
        showGender: true,
        gender: gender,
        size: Dimens.view_portrait_size,
      );
    }
    return Padding(
      padding: EdgeInsets.only(right: Dimens.gap_view_bigger),
      child: child,
    );
  }

  buildAction(String imageName, Function function){
    return SmallWidgets.buildActionIconButton(imageName: imageName, onTap: function, context: context);
  }


  buildLine(){
    return SmallWidgets.buildLine();
  }
  buildLineBigger(){
    return SmallWidgets.buildLineBigger();
  }

  buildArrowRight(){
    return Padding(
        padding: EdgeInsets.only(left: Dimens.gap_view_normal),
      child: Image.asset(PdUtil.getImagePath("ic_arrow_right"), height: Dimens.view_item_icon_height_smaller, fit: BoxFit.fitHeight,),
    );
  }


  jump2Page(Widget page, {bool checkLogin = false}){
    if(checkLogin && !isLogin){
      jump2PageForResult(LoginPage());
    } else {
      NavigatorUtil.pushPage(context, page);
    }
  }
  jump2PageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            if(result.success){
              setState(() {
                isLogin = true;
                refresh();
              });
            }
            break;
        }
      }
    });
  }


  Future<Null> getUserInfo({bool saveUser = false}) async{
    await httpRepository.getUserInfoV2(userId: userId, nickName: nickName).then((resp) {
      if(resp.success){
        user = resp.result;
        userId = user.id;
        userName = user.name;
        gender = user.gender;
        portrait = user.portrait;
        OscUserStatistics statistics = user.statistics;
        tweetCount = statistics.tweet??0;
        blogCount = statistics.blog??0;
        questionsAndAnswersCount = statistics.answer;
        discussCount = statistics.discuss??0;
        focusCount = statistics.follow??0;
        fansCount = statistics.fans??0;

        scores = user.more.radar;
        medals = user.more.medals;

        relation = user.relation;
      }
    });
    if (mounted) {
      setState(() {
        refreshController.refreshCompleted();
      });
    }
  }

  Future<Null> refresh() async{
    getUserInfo();
  }

  Future<Null> reverserRelation({@required int id}) async{
    await httpRepository.reverseRelation(id: id).then((resp) {
      if(resp.success){
        relation = resp.result.relation;
        showTips(relation==2?"关注成功":"取消关注");
      }
    });
    if (mounted) {
      setState(() {
      });
    }
  }

  Future<Null> reverserBlack({@required int id}) async{
    await httpRepository.reverseBlack(id: id).then((resp) {
      if(resp.success){
        user.inBlacklist = resp.result;
        showTips(resp.result?"已拉黑":"已解除拉黑");
      }
    });
    if (mounted) {
      setState(() {
      });
    }
  }

  getRelationImageName(int relation){
    switch(relation){
      case 1:
        relationImageName = "btn_following_both_normal";
        break;
      case 2:
        relationImageName = "btn_following_normal";
        break;
      default:
        relationImageName = "btn_follow_normal";
        break;
    }
    return relationImageName;
  }

  showMoreDialog(){
    double padding = Dimens.gap_view_big;
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context){
          return Container(
            padding: EdgeInsets.only(left: padding, right: padding, bottom: padding),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                buildSheetItem(
                    title: "私信",
                    borderRadius: BorderRadius.only(topLeft: buildRadius(), topRight: buildRadius()),
                    onTap: (){
                      showTips("还没做");
                      Navigator.pop(context);
                    }
                ),
                SmallWidgets.buildLine(),
                buildSheetItem(
                    title: user.inBlacklist?"取消拉黑":"拉黑",
                    borderRadius: BorderRadius.only(bottomLeft: buildRadius(), bottomRight: buildRadius()),
                    onTap: (){
                      reverserBlack(id: userId);
                      Navigator.pop(context);
                    }
                ),
                buildSheetItem(
                    title: "取消",
                    borderRadius: BorderRadius.all(buildRadius()),
                    margin: EdgeInsets.only(top: padding),
                    onTap: (){
                      Navigator.pop(context);
                    }
                ),
              ],
            ),
          );
        }
    );
  }

  buildSheetItem({@required String title, @required BorderRadius borderRadius,
    @required Function onTap, EdgeInsetsGeometry margin = EdgeInsets.zero}){

    double width = ScreenUtil.getScreenW(context);
    double height = Dimens.view_button_height_normal;
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: width,
        height: height,
        alignment: Alignment.center,
        margin: margin,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: borderRadius,
        ),
        child: Text(title, style: MyTextStyle.SHEET_BUTTON,),
      ),
    );
  }
  
  buildRadius(){
    return Radius.circular(Dimens.view_radius_size_normal);
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}